<template>
  <div>
    <s-form-table :fields="fields"
                  create
                  :createButtonClickHandler="add"
                  ref="table"
                  batchDelete
                  :batchDeleteHandler="batchDelete"
                  batchUp
                  :batchUpHandler="batchUp"
                  batchDown
                  :batchDownHandler="batchDown"
                  :transformParams="transformParams"
                  :getData="getData"
                  :columns="columns">
      <template #actions>
        <a-button size="large"
                  type="primary"
                  @click="handleDownload">下载</a-button>
      </template>
      <template slot="time" slot-scope="{ row }">
        {{ formatTime(row.created) }}
      </template>
      <template slot="row-actions"
                slot-scope="{ row }">
        <a-button type="link"
                  @click="edit(row)">编辑</a-button>
        <a-popconfirm title="确定删除该菜品吗？"
                      ok-text="确定"
                      cancel-text="取消"
                      @confirm.stop="del(row)">
          <a-button type="link">删除</a-button>          
        </a-popconfirm>
      </template>
    </s-form-table>
    <add-modal :detail="detail"
               :title="title"
               :refresh="refresh"
               :clearDetail="clearDetail"
               ref="addModal"></add-modal>
  </div>
</template>

<script>
import SFormTable from "@/components/SFormTable";
import addModal from "./addModal";
import api from "@/util/api";
import moment from "moment";
import { message } from "ant-design-vue";
export default {
  components: {
    SFormTable,
    addModal
  },
  filters: {},
  props: {},
  data () {
    return {
      detail: null,
      getUrl: "/api/your-api",
      title: "",
      fields: [
        {
          name: "menuId",
          placeholder: "请选择菜品种类",
          type: "select",
          allowClear: false,
          options: []
        },
        {
          name: "title",
          placeholder:"请输入想查找的菜品名",
          type: "input",        
        }
      ],
      columns: [
        {
          title: "商品ID",
          dataIndex: "id",
          width: "70px",
          fixed: "left",
          align: "center"
        },
        {
          title: "商品标题",
          dataIndex: "title",
          fixed: "left",
          width: "120px",
          align: "left"
        },
        {
          title: "叶子类目",
          dataIndex: "menu",
          width: "120px",
          align: "left"
        },
        {
          title: "卖点",
          dataIndex: "sellPoint",
          width: "120px",
          align: "left"
        },
        {
          title: "已卖数量",
          dataIndex: "sellnum",
          width: "100px",
          align: "left"
        },
        {
          title: "原价",
          dataIndex: "price",
          width: "80px",
          align: "left"
        },
        {
          title: "折扣价",
          dataIndex: "disPrice",
          width: "80px",
          align: "left"
        },
        {
          title: "状态",
          dataIndex: "status",
          width: "80px",
          align: "left"
        },
        {
          title: "创建日期",
          dataIndex: "created",
          slot: "time",
          align: "left"
        },
        {
          title: "更新日期",
          dataIndex: "updated",
          slot: "time",
          align: "left"
        },
        {
          title: "操作",
          dataIndex: "comments",
          align: "center",
          width: "260px",
          type: "actions",
          fixed: "right"
        }
      ]
    };
  },
  watch: {
  },
  created () {
    this.fetchMenuOptions();
  },
  methods: {
    fetchMenuOptions() {
      api.get(`/api/menu/list`, { params: { id: 1 } }).then(res => {
        if (res && Array.isArray(res)) {
          this.fields[0].options = res.map(item => ({
            title: item.text,
            value: item.id
          }));
        } else {
          console.error('数据格式不正确', res.data);
        }
      }).catch(error => {
        console.error('获取菜单选项失败', error);
      });
    },
    formatTime(val) {
      return moment(val).format("YYYY-MM-DD HH:mm:ss")
    },
    getData (params) {
      return new Promise((resolve) => {
        api.get(`/api/disk/list`, { params }).then(res => {
          if (res) {
            const transformedRows = res.rows.map(row => {
              let statusText = '';
              switch (row.status) {
                case 1:
                  statusText = '正常';
                  break;
                case 2:
                  statusText = '优惠中';
                  break;
                case 3:
                  statusText = '下架';
                  break;
                case 4:
                  statusText = '删除';
                  break;
                default:
                  statusText = row.status;
                  break;
              }
              return {
                ...row,
                status: statusText
              };
            });
            resolve({
              page: {
                total: res.total
              },
              data: transformedRows
            })
          }
        });
      });
    },
    transformParams (params) {
      params.rows = params.pageSize
      return params
    },
    refresh () {
      this.$refs.table.search();
    },
    edit (row) {
      this.title = "编辑菜品";
      this.getDetail(row);
    },
    del (row) {
      const formData = new FormData();
      formData.append('ids', row.id)
      api.post(`/api/disk/delete`,formData,{
        headers: {
          'Content-Type': 'multipart/form-data'
        }
        }).then(() => {
        message.success("删除成功");
        this.refresh();
      });
    },
    batchDelete (val) {
      const ids = val.map(item => item.id).join(',')
      const formData = new FormData();
      formData.append('ids', ids)
      api.post(`/api/disk/delete`,formData).then(() => {
        message.success("删除成功");
        this.refresh();
      });
    },
    batchUp(val) {
      const ids = val.map(item => item.id).join(',');
      const formData = new FormData();
      formData.append('ids', ids);
      api.post(`/api/disk/up`, formData).then(() => {
        message.success("批量上架成功");
        this.refresh();
      });
    },
    batchDown(val) {
      const ids = val.map(item => item.id).join(',');
      const formData = new FormData();
      formData.append('ids', ids);
      api.post(`/api/disk/down`, formData).then(() => {
        message.success("批量下架成功");
        this.refresh();
      });
    },
    add () {
      this.title = "新增菜品";
      this.$refs.addModal.visible = true;
    },
    clearDetail () {
      this.detail = null;
    },
    getDetail (val) {
      api.get(`/api/disk/getDiskById?diskId=${val.id}`).then(res => {
      this.detail = res && res.data;
      this.$refs.addModal.visible = true;
      });
    },
    handleDownload() {
      // 获取当前筛选条件
      const params = this.transformParams({
        page: 1,
        pageSize: 9999, // 下载全部数据
        ...this.$refs.table.form
      });
      
      // 调用下载接口
      api.get(`/api/disk/export`, { 
        params,
        responseType: 'blob' // 设置响应类型为blob
      }).then(response => {
        // 创建blob对象
        const blob = new Blob([response], { 
          type: 'application/vnd.ms-excel' 
        });
        
        // 创建下载链接
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        
        // 设置文件名
        const fileName = `菜品列表_${moment().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
        link.download = fileName;
        
        // 触发下载
        document.body.appendChild(link);
        link.click();
        
        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
        
        message.success('下载成功');
      }).catch(error => {
        console.error('下载失败:', error);
        message.error('下载失败，请重试');
      });
    }
  }
};
</script>

<style lang="scss" scoped></style>
